package com.zh.freechat.domain.op_log.impl;

import com.zh.freechat.domain.op_log.entity.OperateLogRecord;
import com.zh.freechat.domain.op_log.repository.OperateLogRecordRepository;
import com.zh.webcommon.common.auth.LoginUserHolder;
import com.zh.webcommon.common.log.OperationLogRecorder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 用户访问操作记录器
 * 同步保存到DB
 * @author ZH
 * @date 19:50 2021/11/5
 */
@AllArgsConstructor
@Component
public class SimpleOperationLogRecorder implements OperationLogRecorder {
    private final OperateLogRecordRepository operateLogRecordRepository;

    /**
     * 记录web用户登录日志
     * @param remoteHost
     * @param name
     */
    @Override
    public void loginLog(String name,String remoteHost)  {
        String operation = "Web端用户(%s)登录成功";
        OperateLogRecord logRecord = new OperateLogRecord(remoteHost, String.format(operation, name), "web login");

        String username = LoginUserHolder.currentUsername();
        logRecord.setUsername(username);
        logRecord.setCreateTime(LocalDateTime.now());
        operateLogRecordRepository.insert(logRecord);
    }

    @Override
    public void accessLog(String operation, String accessMethod,String remoteHost, String accessUri, String reqParams){
        OperateLogRecord logRecord = new OperateLogRecord(remoteHost,operation,accessMethod,reqParams);
        String username = LoginUserHolder.currentUsername();
        logRecord.setUsername(StringUtils.hasText(username)?username:NO_USER);
        logRecord.setCreateTime(LocalDateTime.now());
        operateLogRecordRepository.insert(logRecord);
    }


}
